//! ## 9. Palindrome Number (easy)
//! Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
//!
//! **Follow up**: Could you solve it without converting the integer to a string?
//!
//! #### Example 1:
//! ```txt
//! Input: x = 121
//! Output: true
//! ```
//!
//! #### Example 2:
//!
//! ```txt
//! Input: x = -121
//! Output: false
//! Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
//! ```
//! ### 知识点
//! - 整数整除 `/` 不会保留小数点

pub struct Solution;

impl Solution {
    pub fn solve(x: i32) -> bool {
        if x < 0 {
            return false;
        }
        let mut n = x;
        let mut reverse = 0;
        while n > 0 {
            // 每次 n 取最后一位
            reverse = reverse * 10 + n % 10;
            // 整除 10, 即去掉一位
            n /= 10;
        }
        reverse == x
    }

    /// 转为字符串的解决方式
    pub fn solve2(x: i32) -> bool {
        let x_str = x.abs().to_string();
        let reverse = x_str.chars().rev().collect::<String>();
        x >= 0 && reverse == x_str
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test() {
        assert_eq!(Solution::solve(-123), false);
        assert_eq!(Solution::solve(12321), true);

        assert_eq!(Solution::solve2(-123), false);
        assert_eq!(Solution::solve2(12321), true);
    }
}
